const dither = require('../../dither/dither');

function processDotClampMode(gCode, imageData, gcodeParams) {
    // 应用抖动算法
    dither(imageData.data, imageData.width, imageData.height, 
           gcodeParams.dither, gcodeParams.pixelThreshold);
    
    // if (gcodeParams.scanDir === 'X') {
        processY(gCode, imageData, gcodeParams)
    // } else {
    //     processY(gCode, imageData, gcodeParams);
    // }
}

function processY(gCode, image, gcp) {
    let width = image.width;
    let height = image.height;
    let aSize = gcp.laserABeamSize;
    let ySize = gcp.laserYBeamSize;
    let isRelativeCoord = gcp.isRelativeCoord;
    
    // gCode.note(`P${gcp.dotTime}S${gcp.laserPowerMaxS}`); // 设置点雕刻时间
    gCode.rapid({a: gcp.aOffset, y: (height - 1) * ySize + gcp.yOffset});

    let positionCount = 0; // 计数直
    let lineCount = 0; // 累积行数
    let currentIndex = {x: 0 , y: height - 1}; // 当前 Gcode 最后指向的像素位置, 用于相对坐标计算

    let direction = 0; // 前进
    let directionToggle = 1; // 方向切换
    let serpentine = gcp.serpentine; // 是否启用双向扫描
    if (serpentine) {
        directionToggle = 2;
    }

    for (let x = 0; x < width; x++) { // 从左上角开始扫描
        direction = x % directionToggle; // 切换方向
        let start, end, step;
        if (direction === 0) {
            start = height - 1;
            end = -1;
            step = -1;
        } else {
            start = 0;
            end = height;
            step = 1;
        }
        for (let y = start; y != end; y += step) {  // 遍历每一个像素点
            let grayscale = image.data[x][y]; // 获取灰度值
            // 在打点模式下，每一个像素点都需要检测激光打点 
            if (grayscale < 255) { // 说明该点要打
                if (lineCount > 0) { 
                    if (isRelativeCoord) {
                        gCode.linear({a: lineCount * aSize, y: (start - currentIndex.y + positionCount) * ySize});
                    }else {
                        gCode.linear({a: x * aSize + gcp.aOffset, y: y * ySize + gcp.yOffset});
                    }
                    lineCount = 0;
                } else{
                    if (isRelativeCoord) gCode.linear({y: positionCount * ySize});
                    else gCode.linear({y: y * ySize + gcp.yOffset});
                }
                
                positionCount = 0; // 移动完计数直归零
                currentIndex = {x: x, y: y};
            }
            positionCount += step; // 计数直
        }
        // 一行扫描完成，移动到新一行
        positionCount = 0;
        lineCount++;
    }
    gCode.laserOff(); // 关激光
    if (isRelativeCoord) { // 回零
        gCode.rapid({a: -currentIndex.x * gcp.laserABeamSizeActual - gcp.aOffset, y: -currentIndex.y * ySize - gcp.yOffset});
    }else {
        gCode.rapid({a: 0, y: 0});
    }   
}

module.exports = {processDotClampMode};